package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional//事件
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //用户登录
    @Override
    public ResultInfo login(String username, String password) {
        //1.通过用户名查询
        Employee employee = employeeMapper.findByusername(username);
        if (employee == null) {
            return ResultInfo.error("用户名不存在");
        }
        //2.比较密码
        String passwordWithMd5 = SecureUtil.md5(password);//将传入的密码进行加密
        if (!StringUtils.equals(passwordWithMd5, employee.getPassword())) {
            return ResultInfo.error("用户名密码不正确");
        }
        //3.比较状态码
        if (employee.getStatus() == Employee.STATUS_DISABLE) {
            return ResultInfo.error("当前账户已被禁用");
        }

        //4.返回结果
        return ResultInfo.success(employee);
    }

    //查询所有
    @Override
    public List<Employee> findByName(String name) {
        List<Employee> employeeList = employeeMapper.findByName(name);
        return employeeList;
    }

    //新增用户
    @Override
    public void save(Employee employee) {
        //1.补齐参数
        employee.setPassword(SecureUtil.md5("123")); //设置默认密码，并加密
        employee.setStatus(Employee.STATUS_ENABLE);//z状态

        //2.调用mapper保存
        employeeMapper.insert(employee);
    }

    //通过id查询用户
    @Override
    public Employee findById(String id) {
        return employeeMapper.findById(id);
    }

    //更新用户
    @Override
    public void update(Employee employee) {
        employeeMapper.updateById(employee);
    }
}
